from app.tools import toolsbp
from flask import render_template,request,jsonify,make_response
from app.models import DataTask,AlchemyEncoder,DataDetail,Business,BusinessSteps
from app import db
import json
from datetime import datetime
from app.utils.customer import query_customer_basic_info,query_customer_limit,query_member_xfd,query_member_xfqd
from app.utils.account import query_auth_server_account,query_account_info
from app.utils.util import MyCusEncoder
from app.utils.business import business_mange
@toolsbp.route('/')
@toolsbp.route('/index')
def index():
    common_business = db.session.query(Business).order_by(Business.id.asc()).all()
    return render_template('tools/index.html',title='我的',common_business=common_business)


@toolsbp.route('/data')
def data():
    return render_template('tools/data.html',title='我的')


@toolsbp.route('/data_task', methods=['POST'])
def data_task():
    data = {}
    data['count'] = DataTask.query.filter_by(openid = request.values.get('openid', '', type=str),env = request.values.get('env_tools', 'UAT', type=str).upper()).count()
    data['data'] = DataTask.query.filter_by(openid = request.values.get('openid', '', type=str),env = request.values.get('env_tools', 'UAT', type=str).upper()).order_by(DataTask.create_time.desc()).offset(request.values.get('page', 1, type=int)-1).limit(request.values.get('limit', 10, type=int)).all()
    data['code'] = 0
    data['msg'] = '查询成功'
    return json.dumps(data, cls=AlchemyEncoder)

@toolsbp.route('/data_task/add', methods=['POST'])
def data_task_add():
    if request.method == 'POST':
        task = DataTask()
        task.openid = request.values.get('openid', '', type=str)
        task.env = request.values.get('env_tools', 'UAT', type=str)
        task.phone_prefix = request.values.get('phone_prefix', '158', type=str)
        task.idcard = request.values.get('idcard', '', type=str)
        task.bankcard = request.values.get('bankcard', u'光大银行', type=str)
        task.data_num = request.values.get('data_num', 1, type=int)
        task.is_whitelist = request.values.get('is_whitelist', False, type=bool)
        task.whitelist_system = request.values.get('whitelist_system', u'循环贷', type=str)
        task.is_member = request.values.get('is_member', False, type=bool)
        task.member_type = request.values.get('member_type', '黄金年卡', type=str)
        task.member_system = request.values.get('member_system', u'消费贷', type=str)
        task.is_register = request.values.get('is_register', False, type=bool)
        task.is_bindcard = request.values.get('is_bindcard', False, type=bool)
        task.create_time = datetime.now()
        db.session.add(task)
        db.session.commit()
        return jsonify({'result':1,'message':'数据生成任务添加成功，请刷新表格等待完成'})

@toolsbp.route('/data_task/query', methods=['GET','POST'])
def data_task_query():
    if request.method == 'POST':
        data = {}
        data['count'] = DataDetail.query.filter_by(taskid=request.values.get('taskid', 1, type=int)).count()
        data['data'] = DataDetail.query.filter_by(taskid=request.values.get('taskid', 1, type=int)).order_by(
            DataDetail.create_time.desc()).offset(request.values.get('page', 1, type=int) - 1).limit(
        request.values.get('limit', 10, type=int)).all()
        data['code'] = 0
        data['msg'] = '查询成功'
        return json.dumps(data, cls=AlchemyEncoder)
    taskid =request.values.get('taskid', 1, type=int)
    return render_template('tools/list.html',taskid=taskid)


def common_query_build(data):
    info = request.values.to_dict()
    for key in info:
        data[key] = request.values.get(key)


@toolsbp.route('/query_thumb', methods=['POST'])
def query_thumb():
    data = {}
    result={
        'code':0
    }
    common_query_build(data)
    flag = query_customer_basic_info(data)
    if flag:
        result['code'] = 1
        result['data'] = data
    else:
        result['message'] = '未查询到用户信息'
    res = make_response(json.dumps(result, cls=MyCusEncoder))
    res.mimetype = 'application/json'
    return res

@toolsbp.route('/query_limit', methods=['POST'])
def query_limit():
    data = {}
    result={
        'code':0
    }
    common_query_build(data)
    if data.get('crfuid') is None or data.get('crfuid')=='':
        flag = query_customer_basic_info(data)
        if flag:
            result['code'] = 1
            result['data'] = data
        else:
            result['message'] = '未查询到用户信息'

    flag = query_customer_limit(data)
    res = make_response(json.dumps(result, cls=MyCusEncoder))
    res.mimetype = 'application/json'
    return res

@toolsbp.route('/query_member', methods=['POST'])
def query_member():
    data = {}
    result={
        'code':0
    }
    common_query_build(data)
    if data.get('crfuid') is None or data.get('crfuid')=='':
        flag = query_customer_basic_info(data)
        if flag:
            result['code'] = 1
            result['data'] = data
        else:
            result['message'] = '未查询到用户信息'

    flag = query_member_xfd(data)
    flag = query_member_xfqd(data)
    res = make_response(json.dumps(result, cls=MyCusEncoder))
    res.mimetype = 'application/json'
    return res


@toolsbp.route('/query_account', methods=['POST'])
def query_account():
    data = {}
    result={
        'code':0
    }
    common_query_build(data)
    if data.get('crfuid') is None or data.get('crfuid')=='':
        flag = query_customer_basic_info(data)
        if flag:
            result['code'] = 1
            result['data'] = data
        else:
            result['message'] = '未查询到用户信息'

    flag = query_auth_server_account(data)
    flag = query_account_info(data)
    res = make_response(json.dumps(result, cls=MyCusEncoder))
    res.mimetype = 'application/json'
    return res



@toolsbp.route('/common_manage', methods=['POST'])
def common_manage():
    data = {'message':'','log':''}
    result={
        'code':0
    }

    steps = BusinessSteps.query.filter_by(business=request.values.get('business', '', type=str)).order_by(
        BusinessSteps.sort.desc()).all()
    if  steps:
        common_query_build(data)
        flag = query_customer_basic_info(data)
        query_auth_server_account(data)
        business_mange(data,steps)
        result['message'] = '删除成功'
        result['log'] = data.get('log')
        result['code'] = 1
    else:
        result['message'] = '操作失败，不允许此操作'

    res = make_response(json.dumps(result, cls=MyCusEncoder))
    res.mimetype = 'application/json'
    return res

@toolsbp.route('/common_extras', methods=['GET','POST'])
def common_extras():
    business = db.session.query(Business).filter_by(business_code=request.values.get('business', '', type=str)).first()
    extra = {}
    if business:
        extra = json.loads(business.business_extra)
        if type(extra) is not list:
            extra = {}
    return render_template('tools/extra.html', extra=extra)




